package com.mlink.vs.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.PiccTaskAudio;
import com.mlink.vs.service.PiccTaskAudioService;
import com.mlink.vs.util.StreamUtil;

/**
 * 获取案件所有相关音频文件下载URI列表接口
 * @author Administrator
 */
public class SoundAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;
	
	@Resource
	private PiccTaskAudioService piccTaskAudioService;
	
	@Execute(validator = false)
	public String list(){
		
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("SERVER_URL_FOR_SOUND");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SERVER_URL_FOR_SOUND]未配置，异常退出");
			return null;
		}
		
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		
		Map<String, String> stsMap = new HashMap<String, String>();

		gson = new Gson();
		Map<String, String> mapData = gson.fromJson(indata.toString(),Map.class);
		if (mapData == null)
			return null;
		
		String taskId = (String) mapData.get("taskId");
	
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(taskId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "taskId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			List<PiccTaskAudio> piccTaskAudioList = piccTaskAudioService.findAudioByTaskId(taskId);
			List<String> audioList = new ArrayList<String>();
			if(piccTaskAudioList.size()>0){
				String fileUrl = piccTaskAudioList.get(0).audioUrl;
				String replace = fileUrl.replace("\\","%2f").replace("/","%2f");
				String s=scFileSavePath+replace;
				audioList.add(s);
				rep.getWriter().println(gson.toJson(audioList));
				rep.getWriter().flush();
			}else{
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	@Execute(validator = false)
	public String playSound() {
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("SOUND_STORE_PATH");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SOUND_STORE_PATH]未配置，异常退出");
			return null;
		}

		String audioPath = (String) req.getParameter("sp");
		if (audioPath == null)
			return null;
		audioPath=URLDecoder.decode(audioPath);
		File audioFile = new File(scFileSavePath + audioPath);
		// System.out.println(" ******imageFile****** = " + imageFile.getAbsolutePath());
		
		if (!audioFile.exists())
			return null;
		
		// 根据文件扩展名，形成content-type
		String contentType = "application/octet-stream";
		if (audioPath.toLowerCase().endsWith("amr")){
			contentType = "audio/amr"; 
		} else if (audioPath.toLowerCase().endsWith("mp3")){
			contentType = "audio/mpeg";
		};
		rep.setHeader("Content-Type", contentType);
		
		// 读取音频文件,返回浏览器
		try {
			
			FileInputStream in = new FileInputStream(audioFile);
			ServletOutputStream out = rep.getOutputStream();
			byte [] buffer = new byte[1024]; 
			while(in.read(buffer) != -1){
				out.write(buffer);
			}
			in.close();
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return null;
	}
}